<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="项目" prop="projectId">
        <el-select v-model="queryParams.projectId" placeholder="请选择项目">
          <el-option
            v-for="item in projectList"
            :key="item.projectId"
            :label="item.projectName"
            :value="item.projectId"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="工单标题" prop="woTitle">
        <el-input
          v-model="queryParams.woTitle"
          placeholder="请输入工单标题"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="创建人id" prop="createName">
        <el-input
          v-model="queryParams.createName"
          placeholder="请输入创建人id"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="责任人id" prop="responsibleName">
        <el-input
          v-model="queryParams.responsibleName"
          placeholder="请输入责任人id"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['workorder:workorder:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['workorder:workorder:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="workorderList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
<!--      <el-table-column label="工作联系单主键" align="center" prop="woId" />-->
      <el-table-column label="项目主键" align="center" prop="projectName" />
      <el-table-column label="工单类别主键" align="center" prop="woCatalogName" />
      <el-table-column label="工单标签" align="center" prop="woTag" />
      <el-table-column label="工单编号" align="center" prop="woNumber" />
      <el-table-column label="工单标题" align="center" prop="woTitle" />
      <el-table-column label="事由内容" align="center" prop="woContent">
        <template slot-scope="scope">
          <span>{{ scope.row.woContent | formatRemark }}</span>
          <el-button
            size="mini"
            type="text"
            @click="handleWoContentDetail(scope.row)"
            style="margin-left: 5px;"
          >详情</el-button>
        </template>
      </el-table-column>
      <el-table-column label="责任人" align="center" prop="responsibleName" />
      <el-table-column label="创建人" align="center" prop="createName" />
      <el-table-column label="开始时间" align="center" prop="woStart" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.woStart, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="截止时间" align="center" prop="woEnd" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.woEnd, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
<!--      <el-table-column label="活动主键" align="center" prop="avtivityId" />-->
<!--      <el-table-column label="协助人id" align="center" prop="helpId" />-->
<!--      <el-table-column label="抄报人id" align="center" prop="reporterId" />-->
<!--      <el-table-column label="抄送人id" align="center" prop="copyId" />-->
<!--      <el-table-column label="工单状态,1-待处理, 2-通过, 3-退回" align="center" prop="woStatus" />-->
<!--      <el-table-column label="创建时间" align="center" prop="woDate" width="180">-->
<!--        <template slot-scope="scope">-->
<!--          <span>{{ parseTime(scope.row.woDate, '{y}-{m}-{d}') }}</span>-->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['workorder:workorder:edit']"
          >修改</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改工单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="80%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="项目" prop="projectId">
              <el-cascader v-model="value" :options="options" @change="handleChangeOfcheckUser"></el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工单标题" prop="woTitle">
              <el-input v-model="form.woTitle" placeholder="请输入工单标题" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="开始时间" prop="woStart">
              <el-date-picker clearable
                              v-model="form.woStart"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="请选择开始时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="截止时间" prop="woEnd">
              <el-date-picker clearable
                              v-model="form.woEnd"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="请选择截止时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="工单类别" prop="woCatalogId">
              <el-select v-model="form.woCatalogId" placeholder="工单类别" clearable>
                <el-option
                  v-for="item in woCatalogList"
                  :key="item.woCatalogId"
                  :label="item.woCatalogName"
                  :value="item.woCatalogId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工单标签" prop="woTag" style="width: 300px;">
              <el-input v-model="form.woTag" placeholder="请输入工单标签" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="事由内容">
          <editor v-model="form.woContent" :min-height="192"/>
        </el-form-item>
        <el-form-item label="工单编号" v-show="isUpdate">
          <el-input v-model="form.woNumber" placeholder="请输入工单编号"/>
        </el-form-item>
        <el-row>
          <el-col :span="8">
            <el-form-item label="责任人" prop="responsibleName">
              <el-input readonly v-model="form.responsibleName"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item>
              <el-button @click="handleResponsible">选择负责人</el-button>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="电话" prop="responsibleNameTel">
              <el-input readonly v-model="form.responsibleNameTel"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="协助人" prop="helpName">
              <el-input readonly v-model="form.helpName" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item>
              <el-button @click="handleHelp">选择协助人</el-button>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="抄报人" prop="reporterName">
              <el-input readonly v-model="form.reporterName" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item>
              <el-button @click="handleReporter">选择抄报人</el-button>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="抄送人" prop="copyName">
              <el-input v-model="form.copyName" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item>
              <el-button @click="handleCopy">选择抄送人</el-button>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="工单图片">
          <ImageUpload :limit="3" v-model="form.images"></ImageUpload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
<!--    工单内容详情-->
    <el-dialog  title="工单内容详情" :visible.sync="gdDialog" width="40%" style="margin-top: 200px">
      <div  v-html="form.woContent"></div>
    </el-dialog>
<!--    选择按钮的组件-->
    <el-dialog :title="title" :visible.sync="xzOpen" style="margin-top: 200px">
      <choose-user :projectId="form.projectId" @getData="getData"></choose-user>
    </el-dialog>


  </div>
</template>

<script>
import { listWorkorder, getWorkorder, delWorkorder, addWorkorder, updateWorkorder} from "@/api/workorder/workorder";
import {getCascader, listProject} from "@/api/project/project";
import {listWorkorderType} from "@/api/workorder/workorderType";
import  ChooseUser from "@/components/ChooseUser";
import  DeptTree from "@/components/DeptTree";
import {getResponsibleNameTel} from "@/api/system/user";

export default {
  name: "Workorder",
  components:{ChooseUser,DeptTree},
  data() {
    return {
      //判断是不是修改，是修改就展示
      isUpdate:false,
      formattedDate:"",
      // 工单序号
      orderNumber: 1 ,
      // 选择按钮的开关
      xzOpen: false,
      // 工单类别下拉绑定值
      woCatalogList:[],
      // 级联选择器绑定值
      value: [],
      // 级联选择器绑定值
      options:[],
      //详情开关
      gdDialog: false,
      // 项目下拉绑定值
      projectList:[],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 工单表格数据
      workorderList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        projectId: null,
        projectName: null,
        woTitle: null,
        createId: null,
        responsibleId: null,
        responsibleName: null,
        createName: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      flog:0,
    };
  },
  created() {
    this.getList();
    this.getProjectList();
    this.getCascaderList();
    this.getWorkOrderTypeList();
  },
  filters: {
    formatRemark (value) {
      return value.length > 3 ? value.substring(0, 3) + '...' : value;
    },
  },
  methods: {
    //级联改变的时候触发，选择的责任人、协助人、抄报人、抄送人内容清空重新选择
    handleChangeOfcheckUser(){
      this.form.responsibleName = "";
      this.form.responsibleNameTel = "";
      this.form.helpName = "";
      this.form.reporterName = "";
      this.form.copyName = "";
      this.form.helpId = "";
      this.form.reporterId = "";
      this.form.copyId = "";
    },
    /** 获取选择人员 */
    getData(val){
      if(this.flog === 1){
        this.form.responsibleName = val.label;
        this.form.responsibleId = val.id;
        //根据负责人查电话
        getResponsibleNameTel(this.form.responsibleId)
          .then(response => {
            this.form.responsibleNameTel = response.msg;
          })
      }else if(this.flog === 2){
        this.form.helpName = val.label;
        this.form.helpId = val.id;
      }else if (this.flog === 3){
        this.form.reporterName = val.label;
        this.form.reporterId = val.id;
      }else{
        this.form.copyName = val.label;
        this.form.copyId = val.id;
      }
      this.xzOpen = false;
    },
    /** 选择按钮 */
    handleResponsible(){
      if(this.value.length === 0){
        this.$message({
          message: "请选择项目",
          type: "warning",
        });
        this.xzOpen = false;
        return;
      }
      this.form.projectId = this.value[0];
      this.xzOpen = true;
      this.title = "选择负责人";
      this.flog = 1;
    },
    handleHelp(){
      if(this.value.length === 0){
        this.$message({
          message: "请选择项目",
          type: "warning",
        });
        this.xzOpen = false;
        return;
      }
      this.form.projectId = this.value[0];
      this.xzOpen = true;
      this.title = "选择协助人";
      this.flog = 2;
    },
    handleReporter(){
      if(this.value.length === 0){
        this.$message({
          message: "请选择项目",
          type: "warning",
        });
        this.xzOpen = false;
        return;
      }
      this.form.projectId = this.value[0];
      this.xzOpen = true;
      this.title = "选择抄报人";
      this.flog = 3;
    },
    handleCopy(){
      if(this.value.length === 0){
        this.$message({
          message: "请选择项目",
          type: "warning",
        });
        this.xzOpen = false;
        return;
      }
      this.form.projectId = this.value[0];
      this.xzOpen = true;
      this.title = "选择抄送人";
      this.flog = 4;
    },
    // 工单类别下拉框
    getWorkOrderTypeList(){
      listWorkorderType().then(resp => {
        this.woCatalogList = resp.rows;
        if(resp.data.length > 0){
          this.form.woCatalogId = resp.data[0].woCatalogId;
        }
      })
    },
    // 级联下拉框
    getCascaderList(){
      getCascader().then(resp => {
        this.options = resp.data;
      })
    },
    /** 工单 内容详情 */
    handleWoContentDetail(row){
      this.gdDialog = true;
      this.form.woContent = row.woContent;
    },
    /** 查询项目列表 */
    getProjectList() {
      listProject().then(resp => {
        this.projectList = resp.rows;
      })
    },
    /** 查询工单列表 */
    getList() {
      this.loading = true;
      listWorkorder(this.queryParams).then(response => {
        this.workorderList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        woId: null,
        woCatalogId: null,
        woCatalogName: null,
        projectId: null,
        avtivityId: null,
        woNumber: null,
        woStart: null,
        woEnd: null,
        woTag: null,
        woTitle: null,
        woContent: null,
        createId: null,
        responsibleId: null,
        helpId: null,
        reporterId: null,
        copyId: null,
        woStatus: null,
        woDate: null,
        responsibleNameTel:null,
        woImageSrc:null,
        images:null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.woId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.isUpdate = false;
      this.value = [];
      this.open = true;
      this.title = "添加工单";
      //工单编号的格式为 “GD-时间-序号”, 例如2023年6月29日的第一个工单的编号即为GD-20230629-0001
      // 以此类推, 最后4位表示序号,下一个工单的编号就是GD-20230629-0002.  2023年6月30日的第一个工单编号为GD-20230630-0001.
      const now = new Date(); // 获取当前日期
      const year = now.getFullYear();
      const month = ('0' + (now.getMonth() + 1)).slice(-2); // 月份从0开始，所以加1，并确保两位数
      const day = ('0' + now.getDate()).slice(-2); // 确保两位数
      this.formattedDate = `${year}${month}${day}`; // 拼接成 YYYYMMDD 的格式
      this.form.woNumber  = `GD-${this.formattedDate}-${this.orderNumber.toString().padStart(4, '0')}`;
      this.orderNumber++; // 增加序号
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.isUpdate = true;
      const woId = row.woId || this.ids
      getWorkorder(woId).then(response => {
        this.form = response.data;
        this.value[0] = row.projectId;
        this.value[1] = row.avtivityId;
        // 获取负责人电话
        getResponsibleNameTel(row.responsibleId)
          .then(response => {
            this.form.responsibleNameTel = response.msg;
          })
        this.open = true;
        this.title = "修改工单";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.woId != null) {
            this.form.projectId = this.value[0]
            this.form.avtivityId = this.value[1]
            updateWorkorder(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            this.form.projectId = this.value[0]
            this.form.avtivityId = this.value[1]
            addWorkorder(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const woIds = row.woId || this.ids;
      this.$modal.confirm('是否确认删除工单编号为"' + woIds + '"的数据项？').then(function() {
        return delWorkorder(woIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    }
  }
};
</script>
